package server

import (
	"context"
	"github.com/google/uuid"
	"gorm.io/gorm"
	"love-link/love-server/basic/handler/model"
	__ "love-link/love-server/basic/proto"
)

type Server struct {
	__.UnimplementedVipServer
}

func (s Server) UpdateUser(_ context.Context, in *__.UpdateUserReq) (*__.UpdateUserResp, error) {
	//TODO implement me
	var user model.User
	user = model.User{
		Model: gorm.Model{
			ID: uint(in.ID),
		},
		Username: in.Username,
		Vip:      in.Vip,
		VipTime:  in.VipTime,
	}
	err := model.Update(&user, in.ID)
	if err != nil {
		return &__.UpdateUserResp{
			Code: 0,
			Msg:  "修改失败",
		}, nil
	}
	return &__.UpdateUserResp{
		Code: 200,
		Msg:  "修改成功",
	}, nil

}

func (s Server) CreateOrder(_ context.Context, in *__.CreateOrderReq) (*__.CreateOrderResp, error) {

	orderId := uuid.NewString()

	var order model.Order
	order = model.Order{
		UserId:  int(in.UserId),
		VipId:   int(in.VipId),
		OrderId: orderId,
		Price:   float64(in.Price),
	}

	err := model.CreateOrder(&order)
	if err != nil {
		return &__.CreateOrderResp{
			Code: 0,
			Msg:  "订单创建失败",
		}, nil
	}
	return &__.CreateOrderResp{
		Code: 200,
		Msg:  "订单生成成功",
	}, nil

}

func (s Server) FindVip(_ context.Context, in *__.FindVipReq) (*__.FindVipResp, error) {

	var VipType model.VipType
	err := model.FindVip(&VipType)
	if err != nil {
		return &__.FindVipResp{
			VipType: nil,
			Code:    0,
			Msg:     "查询失败",
		}, nil
	}
	return &__.FindVipResp{
		Code: 200,
		Msg:  "查询成功",
	}, nil
}

func (s Server) CreateVip(_ context.Context, in *__.CreateVipReq) (*__.CreateVipResp, error) {

	var VipCharge model.VipCharge
	if in.Price < 0 {
		return &__.CreateVipResp{
			Code: 0,
			Msg:  "价格不能小于等于0",
		}, nil
	}

	if in.Type == "" {
		return &__.CreateVipResp{
			Code: 0,
			Msg:  "支付方式不能为空",
		}, nil
	}

	VipCharge = model.VipCharge{
		UserID:  int(in.UserID),
		OrderID: int(in.OrderID),
		Status:  in.Status,
		Price:   float64(in.Price),
		Type:    in.Type,
	}

	err := model.CreateVip(&VipCharge)
	if err != nil {
		return &__.CreateVipResp{
			Code: 0,
			Msg:  "充值失败",
		}, nil
	}
	return &__.CreateVipResp{
		Code: 200,
		Msg:  "充值成功",
		Data: int64(VipCharge.ID),
	}, nil
}
